package com.five.matebook.activity;


import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.five.matebook.R;

public class MuliTaskCounting {
    private static final String TAG = MuliTaskCounting.class.getSimpleName();
    public interface ICallback {
        void onArriveTarget(int count, boolean ret);
    }

    private int targetCount;
    private volatile int count;
    private ICallback callback;
    private boolean callbackOnMainThread;
    private Handler handler = new Handler(Looper.getMainLooper());
    public MuliTaskCounting(ICallback callback) {
        this(-1, callback);
    }
    public MuliTaskCounting(int targetCount, ICallback callback) {
        this(targetCount, callback, true);
    }
    public MuliTaskCounting(int targetCount, ICallback callback, boolean callbackOnMainThread) {
        this.targetCount = targetCount;
        this.callback = callback;
        this.callbackOnMainThread = callbackOnMainThread;
    }

    public void setTargetCount(int targetCount) {
        this.targetCount = targetCount;
    }

    private volatile boolean mResult = true;
    public synchronized void addCount(boolean successed) {
        if (targetCount <= 0) {
            return;
        }
        count ++;
        mResult &= successed;
        Log.d(TAG, String.format("addCount() successed=%s, count=%d, targetCount=%d", successed, count, targetCount));

        if (count == targetCount && callback != null) {
            if (callbackOnMainThread) {
                handler.post(() -> {
                    callback.onArriveTarget(targetCount, mResult);
                });
            } else {
                callback.onArriveTarget(targetCount, mResult);
            }
        }
    }
}
